﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model.Catalog;
using System.Web.Security;
using System.Web.Profile;


namespace OnlineFloralShop
{
    public partial class Checkout : System.Web.UI.Page
    {

        //EVENTS
        protected void Page_Load(object sender, EventArgs e)
        {
            
        
            //---------------------------------------------------------------//
            //Bind All Locations
            if (!IsPostBack)
            {
                //---------Locations----------------------------//
                drpLocation.DataSource = Order.GetAllLocations();
                drpLocation.DataTextField = "LocationName";
                drpLocation.DataValueField = "LocationId";
                drpLocation.DataBind();
                drpLocation.Items.Add(new ListItem("---Select---", "0"));
                drpLocation.Items.FindByText("---Select---").Selected = true;


                //---------Locations----------------------------//
                drpMessage.DataSource = Model.Catalog.Category.GetAllCategories();
                drpMessage.DataTextField = "CategoryName";
                drpMessage.DataValueField = "CategoryId";
                drpMessage.DataBind();
                drpMessage.Items.Add(new ListItem("---Select---", "0"));
                drpMessage.Items.FindByText("---Select---").Selected = true;

                //----------Messages----------------------------//
                drpMessageListByCaegoryId.Items.Add(new ListItem("---Select Message---", "0"));
                drpMessageListByCaegoryId.Enabled = false;

                //Set title Shipping
                Title = "Delivery Information - Online Floral Shop";
            }


            //----------------------------------------------------------------//
            //Check cart differen null
            if (((Dictionary<string, int>)Session["cart"]).Count < 1)
            {
                Response.Redirect("~/Cart.aspx");
            }
            else
            {
                //show cart details
                ListView_Cart.DataSource = ((Dictionary<string, int>)Session["cart"]);
                ListView_Cart.DataBind();
            }



            //-----------------------------------------------------------------//
            //Show Information Account
            if (User.Identity.IsAuthenticated)
            {
                lbName.Text = HttpContext.Current.Profile["Name"].ToString();
                lbAddress.Text = HttpContext.Current.Profile["Address"].ToString();
                lbSex.Text = HttpContext.Current.Profile["Sex"].ToString();
          //    lbLocation.Text = Model.Catalog.Order.GetLocationByLocationId(HttpContext.Current.Profile["LocationId"].ToString()).Rows[0]["LocationName"].ToString();
                lbPhone.Text = HttpContext.Current.Profile["Phone"].ToString();
                lbEmail.Text = Membership.GetUser(User.Identity.Name).Email;
            }

        }

        protected void btnShipNext_Click(object sender, EventArgs e)
        {
            //------------------------------------------------------------------------------------//
            //validate form New Address
            if(rbtnNewAddress.Checked == true && (txtAddress.Text == "" || txtEmail.Text == "" || txtName.Text == "" || txtPhone.Text == "" || drpLocation.SelectedValue == "0"))
            {
                
                lbnotify.Text = "Input all field have (*)";
                return; 
            }

            //----Variables----
            string name = "";
            string address = "";
            string phone = "";
            string email = "";
            string locationid = "";
            string sex ="";
            string message = "";
            string timedelivery = "";
           

            //------------------------------------------------------------------------------------//
            //Store Shipping information
            if (rbtnSameAddress.Checked)
            {
                name = lbName.Text;
                address = lbAddress.Text;
                phone = lbPhone.Text;
                email = lbEmail.Text;
                locationid = lbLocation.Text;
                sex = lbSex.Text;

            }
            else
            {
                name = txtName.Text;
                address = txtAddress.Text;
                phone = txtPhone.Text;
                email = txtEmail.Text;
                locationid = drpLocation.SelectedValue;
                sex = drpSex.SelectedValue;
            }

            //--get message
            if (txtMessage.Text != "Write message...")
            {
                message = txtMessage.Text;
            }
            else
            {
                message = drpMessageListByCaegoryId.SelectedValue;
            }

            //--choose day delivery
            if (rbtnEarliest.Checked)
            {
                timedelivery = ""; //time default
            }
            else
            {
               timedelivery = txtDateDelivery.Text;
            }

            //----------------------------------------------------------------------------------//
            //store to shipping session
            StoreShippingData(name, address, phone, email, locationid, sex, message, timedelivery);


            //-----------------------------------------------------------------------------------//
            //Show address pay and shipping
            //Payment Address
            lbPayName.Text = HttpContext.Current.Profile["Name"].ToString();
            lbPayAdd.Text = HttpContext.Current.Profile["Address"].ToString();
            lbPaySex.Text = HttpContext.Current.Profile["Sex"].ToString();
            //lbPayLocation.Text = Model.Catalog.Order.GetLocationByLocationId(HttpContext.Current.Profile["LocationId"].ToString()).Rows[0]["LocationName"].ToString();
            lbPayPhone.Text = HttpContext.Current.Profile["Phone"].ToString();
            lbPayEmail.Text = Membership.GetUser(User.Identity.Name).Email;

            //Shipping Address
            lbShipName.Text = name;
            lbShipAdd.Text = address;
            lbShipEmail.Text = email;
            lbShipPhone.Text = phone;
            lbShipSex.Text = sex;
          //  lbShipLocation.Text = Model.Catalog.Order.GetLocationByLocationId(locationid).Rows[0]["LocationName"].ToString();
            //--------------------------------------------------------------------------------------//

            lbSub_total.Text = decimal.Floor(GetTotalPriceInCart()).ToString() + " $";
            lbCost.Text = decimal.Floor(decimal.Parse(Order.GetLocationByLocationId(((Dictionary<string, string>)Session["Shipping"])["LocationId"]).Rows[0]["Cost"].ToString()))+" $";
            lbTotal.Text = (decimal.Floor(GetTotalPriceInCart()) + decimal.Floor(decimal.Parse(Order.GetLocationByLocationId(((Dictionary<string, string>)Session["Shipping"])["LocationId"]).Rows[0]["Cost"].ToString()))) + " $";


            //go to view 2: order confrim
            MultiView_Checkout.ActiveViewIndex = 1;
             
        }

        

        protected void btnPayPrev_Click(object sender, EventArgs e)
        {
            MultiView_Checkout.ActiveViewIndex = 0;
        }




        protected void btnPayNext_Click(object sender, EventArgs e)
        {
            //Check Confim Order
            if (!cbxAcceptOrder.Checked)
            {
                lbConfrimMessage.Text = "Error: You must agree to the Terms & Conditions!";
            }
            else
            {
                //set variables
                string name = ((Dictionary<string, string>)Session["Shipping"])["Name"];
                string address = ((Dictionary<string, string>)Session["Shipping"])["Address"];
                string phone = ((Dictionary<string, string>)Session["Shipping"])["Phone"];
                string email = ((Dictionary<string, string>)Session["Shipping"])["Email"];
                string locationid = ((Dictionary<string, string>)Session["Shipping"])["LocationId"];
                string sex = ((Dictionary<string, string>)Session["Shipping"])["Sex"];
                string message = ((Dictionary<string, string>)Session["Shipping"])["Message"];
                string timedelivery = ((Dictionary<string, string>)Session["Shipping"])["Time"];

                //Add new order
                if (Order.AddNewOrder(User.Identity.Name, timedelivery, name, address, locationid, email, sex, phone, message, txtCreditCardNumber.Text) > 0)
                {
                    int OrderId = int.Parse(Order.GetOrderIdLastestByUserName(User.Identity.Name).Rows[0]["OrderId"].ToString());

                    //Add all order details
                    foreach (KeyValuePair<string, int> kvp in ((Dictionary<string, int>)Session["cart"]))
                    {
                        Order.AddNewAOrderDetail(OrderId, kvp.Key, kvp.Value, decimal.Parse(Model.Catalog.Product.GetProductDetailByProductId(kvp.Key).Rows[0]["Price"].ToString()));
                    }

                    //Clear session cart and Shipping Address
                    ((Dictionary<string, int>)Session["cart"]).Clear();
                    ((Dictionary<string, string>)Session["Shipping"]).Clear();

                    //Title
                    Title = "Order confrimation & Payment - Online Floral Shop";

                    //go to view Result Order
                    MultiView_Checkout.ActiveViewIndex = 2;
                }
                else
                {

                }
            }

        }



        //--------------------------------------------------------------------------------//
        //Bind message from data using AJAX
        protected void drpMessage_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Bind message from data using AJAX
            drpMessageListByCaegoryId.Enabled = true;
            drpMessageListByCaegoryId.DataSource = Order.GetMessagesByCategoryId(drpMessage.SelectedValue);
            drpMessageListByCaegoryId.DataTextField = "Contents";
            drpMessageListByCaegoryId.DataValueField = "Contents";
            drpMessageListByCaegoryId.DataBind();

            if (Order.GetMessagesByCategoryId(drpMessage.SelectedValue).Rows.Count < 1)
            {
                drpMessageListByCaegoryId.Items.Add(new ListItem("---No Messages of thi Category---", "0"));
            }
        }

        //METHODS
        //----------------------------------------------------------------------//
        //Get total price of current cart
        public decimal GetTotalPriceInCart()
        {
            decimal total = 0;
            if (Session["cart"] != null)
            {
                foreach (KeyValuePair<string, int> kvp in ((Dictionary<string, int>)Session["cart"]))
                {
                    total += kvp.Value * decimal.Parse(Model.Catalog.Product.GetProductDetailByProductId(kvp.Key).Rows[0]["Price"].ToString());
                }
                return decimal.Floor(total);

            }
            return 0;
        }

        //------------------------------------------------------------------------//
        //Method storo to shipping session data
        void StoreShippingData(string name, string address, string phone, string email, string locationid, string sex, string message, string datedelivery)
        {
            string[] param = { "Name", "Address", "Phone", "Email", "LocationId", "Sex", "Message", "Time" };
            string[] value = { name, address, phone, email, locationid, sex, message, datedelivery };

            for (int i = 0; i < param.Length; i++)
            {
                if (((Dictionary<string, string>)Session["Shipping"]).ContainsKey(param[i]))
                {
                    ((Dictionary<string, string>)Session["Shipping"])[param[i]] = value[i];
                }
                else
                {
                    ((Dictionary<string, string>)Session["Shipping"]).Add(param[i], value[i]);
                }
            }
        }

    }
}
